package com.dingding.transfer.stamper.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.dingding.transfer.stamper.constant.ApprovalPara;
import com.dingding.transfer.stamper.dto.BaseResult;
import com.dingding.transfer.stamper.dto.FormComponent;
import com.dingding.transfer.stamper.entity.ProcessDetail;
import com.dingding.transfer.stamper.entity.User;
import com.dingding.transfer.stamper.service.BusinessService;
import com.dingding.transfer.stamper.service.DingDingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/4/6 15:31
 **/
@Slf4j
@Component
public class PushRecordInstance implements TaskInstanceProcessor{
    @Autowired
    private DingDingService dingDingService;

    @Autowired
    private BusinessService businessService;

    @Override
    public boolean match(String name) {
        return StringUtils.contains(name, ApprovalPara.PUSH_RECORD);
    }

    @Override
    public void handleTaskStart(JSONObject jsonObject) {
        log.info("推送申请单 回调");
        // 定义的推送申请单 的表单第一条为姓名，第二条为设备
        List<FormComponent> formDetails = dingDingService.getFormDetails(
                jsonObject.getString("corpId"),jsonObject.getString("processInstanceId"));
        if(CollectionUtil.isNotEmpty(formDetails)){
            String uuid = businessService.getDeviceId(formDetails.get(1).getValue());
            User userInfo = businessService.findUserInfo(formDetails.get(0).getValue());
            if(userInfo == null){
                log.error("根据用户名{}没有找到设备Id{}对应的用户信息",formDetails.get(0).getValue(),uuid);
                return;
            }
            ProcessDetail applyDetail = businessService.findApplyDetail(userInfo.getUserid(),uuid);
            if(applyDetail != null){
                int pushTime = 0;
                while(pushTime < 4){
                    BaseResult baseResult = businessService.pushRecord(uuid,applyDetail.getApplyId().toString());
                    if(baseResult.isSuccess()){
                        break;
                    }else{
                        pushTime++;
                        try {
                            Thread.sleep(30000l);
                        } catch (InterruptedException e) {}
                        log.error("失败重新推送第{}次",pushTime);
                    }
                }
            }else {
                log.error("没有找到对应用户{}，对应设备{}的申请记录",userInfo.getUserid(),uuid);
            }
        }
    }
}
